home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 8807 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.6 KB

  1. Path: keats.ugrad.cs.ubc.ca!not-for-mail
  2. From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: C unions
  5. Date: 6 Mar 1996 01:48:27 -0800
  6. Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
  7. Message-ID: <4hjn1bINN5bb@keats.ugrad.cs.ubc.ca>
  8. References: <367cc$0359.14a@news.express.ca>
  9. NNTP-Posting-Host: keats.ugrad.cs.ubc.ca
  10.  
  11. In article <367cc$0359.14a@news.express.ca>,
  12. Gary Chan <gchan@express.ca> wrote:
  13. >I need a C union that allows me to freely interpret an integer 
  14. >separately as the least significant byte or the most significant byte, 
  15. >and as a single integer.  
  16. >
  17. >Can someone help me get started on this?
  18.  
  19. Sorry, you can't do that, unless you can depend on implementation-defined
  20. behavior of unions.
  21.  
  22. It is illegal to access the value of a union member through a different union
  23. member.
  24.  
  25. At the very best, your attempt will result in code that depends on the byte
  26. ordering of the implementation. Furthmore, structure packing and alignment will
  27. play a role as well, as will the integer size! You are assuming that it is 16
  28. bits, correct?
  29.  
  30. The proper way to access the lower eight bits of the integer is to bitwise AND
  31. it with 0xff to mask out all bits except the lower eight. That portably gives
  32. you the least significant eight bits. To get the next set of eight bits from
  33. the integer, you shift it right by eight, and do the same AND. That gets you
  34. your high order byte of a 16-bit integer:
  35.  
  36. #define HILO(N,H,L) ((H) = (N) >> 8 & 0xff, (L) = (N) & 0xff)
  37.  
  38. This macro splits the quantity N (assumed to be 0-65535) into a high-order and
  39. low-order byte values stored in the lvalues represented by H and L.
  40. -- 
  41.  
  42.